/**
 * @description  : 应用入口
 * @descriptionDetail : 应用入口
 * @copyright    : 浙江烟草
 * @author       : mc
 * @create       : 2022-09-04 11:09:19
 */

import Vue from "vue";
import App from "./App";
import store from "./store";
import webDB from "@/common/database.js";
import modal from "@/common/modal.js";
import deviceApi from "@/platforms/default.platform.service.js";
import theme from "@/theme/variables.scss.js";
import globalDoc from "@/config/globalDoc";
import { commonMixin } from "@/config/commonMixin.js";
import routerParam from "@/config/routerParam.js";
import { get, remove, set } from "@/config/routerStorage.js";
import VueCryptojs from "vue-cryptojs";
import VTooltip from "v-tooltip";
import commonService from "@/service/common/common.service";
import loginService from './service/common/login.service';
import {isDD,isWorkWechat,isIOS, isEmpApp} from './common/util';
// 引入全局uView
import uView from "uview-ui";
// 数据字典
import dicData from "@/common/common_dic.js";
// 引入mescroll，注册全局组件
import MescrollBody from "@/components/mescroll-uni/mescroll-body.vue";
import { FILE_GROUP_TYPE } from "@/service/common/mapping/enum.js";
import { DD_MODEL, noIOS,noBrowser,tip } from "@/config/setting.config";

const toast = (title, duration = 1500, mask = false, icon = "none") => {
  // 统一提示方便全局修改
  if (Boolean(title) === false) {
    return;
  }
  uni.showToast({
    title,
    duration,
    mask,
    icon,
  });
};

Vue.use(VueCryptojs);

App.mpType = "app";
Vue.use(uView);
Vue.use(globalDoc);

Vue.use(VTooltip);

const app = new Vue({
  ...App,
});

Vue.use(dicData, app);
Vue.component("MescrollBody", MescrollBody);

Vue.config.productionTip = false;
Vue.prototype.$api = {
  toast,
  webDB,
};
Vue.prototype.$theme = theme;
Vue.prototype.$store = store;
Vue.prototype.$FILE_GROUP_TYPE = FILE_GROUP_TYPE;
// 注册alert、confirm组件
Vue.prototype.$modal = modal;
// 挂载页面缓存参数
Vue.prototype.$rp = routerParam;
Vue.prototype.$storage = {
  set,
  get,
  remove,
};
// 注意：此分支不能与其他分支合并！！！
Vue.prototype.$deviceApi = deviceApi;
// 全局混入，监听路由变化，动态设置钉钉标题
Vue.prototype.$r = require("@/page_modules/index.js");
Vue.mixin(commonMixin);
 uni.clearStorageSync();
// 第三方人员签名页面适用于各个平台，不做限制
if (location.href.indexOf("pages/commonPage/signDoc") !== -1) {
  let signLoginName = getUrlParam("un");
  if (signLoginName) {
    showMcModal(signLoginName);
    hideLanuch();
  } else {
    alert("您没有访问权限");
  }
} // 钉钉免登授权
else if (isDD()) {
  // 移动平台对接
  let agId = getAgentIdFromHref();
  deviceApi
    .ddLogin(agId)
    .then((data) => {
      // 获取登录用户信息，并初始化页面
      console.log("账号：===" + data.loginname);
      if (process.env.NODE_ENV == "production" && vaildDevUsers(data.loginname)) {
        showMcModal();
        hideLanuch();
      } else {
        let mobile = data.mobilephone || '';
        if (!mobile) return alert('手机号码获取失败,请先在OA系统维护手机号！');
        mobile = rsaUtil.encrypt(mobile);
        initPDingByMobile(mobile);
      }
    })
    .catch((err) => {
      let errInfo = `登录失败,失败原因：${err}`;
      alert(errInfo);
    });
} else if (isWorkWechat()) {
	console.log("NM-企业微信-start");
	// eslint-disable-next-line no-underscore-dangle
	const _code = getUrlParam('code');
	// 微信端
	let agId = getAgentIdFromHref();
	console.log("NM-企业微信",_code);
	// 限制ios系统 fsx 2023-12-27 开始
	if(noIOS && isIOS()) {
		alert("友情提示：禁止使用苹果设备登录。");
	} else {
		deviceApi.wxLogin(agId,_code).then(data => {
			// 获取登录用户信息，并初始化页面
			console.log("账号：===" + data.loginname);
			if (process.env.NODE_ENV == "production" && vaildDevUsers(data.loginname)) {
				showMcModal();
				hideLanuch();
			} else {
				if(Number(data.code) === 0 && data.success === true) {
				  loginWX(data)
				} else if(Number(data.code) === 996) {
					showMcModal();
					hideLanuch();
				}
			}
		}).catch(err => {
			let errInfo = `登录失败,失败原因：${err}`;
			alert(errInfo);
		});
	}
	// 限制ios系统 fsx 2023-12-27 结束
} else if (isEmpApp()) {
  console.log("HN---EMP-start");
  const _userToken = getUrlParam('usertoken');
  const _token = getUrlParam('token');
  // emp
  deviceApi.empLogin(_userToken,_token).then(data => {
    // 获取登录用户信息，并初始化页面
    if (process.env.NODE_ENV == "production" && vaildDevUsers(data.loginname)) {
      showMcModal();
      hideLanuch();
    } else {
      if(Number(data.code) === 0 && data.success === true) {
        loginWX(data)
      } else if(Number(data.code) === 996) {
        showMcModal();
        hideLanuch();
      }
    }
  }).catch(err => {
    let errInfo = `登录失败,失败原因：${err}`;
    alert(errInfo);
  });
} else {
  // 限制浏览器系统 fsx 2023-12-27 开始
  if (noBrowser) {
    alert(tip);
  } else {
    // TODO 开发测试使用
    if (process.env.NODE_ENV === "production") {
      if (process.env.VUE_APP_ENV == 'tdt') {
        showMcModal();
        hideLanuch();
      } else {
        alert(tip);
      }
    } else {
      showMcModal();
      hideLanuch();
    }
  }
  // 限制ios系统 fsx 2023-12-27 结束
}

function loginWX(dr) {
  hideMcModal();
  hideLanuch();
  uni.setStorageSync("tk", dr.bean.tk);
  sessionStorage.setItem("tk", dr.bean.tk);
  store.state.userInfo = dr.bean;
  uni.setStorageSync("user", JSON.stringify(dr.bean));
  // 初始化字典数据
  app.$u.dic.dicDataInit();
  commonService.area();
  // 页面挂载
  app.$mount();
}

function vaildDevUsers(userName) {
  let devUsers = []; // 字符串数组，字符串表示方便在钉钉环境中登录所有指定用户账号
  return devUsers.includes(userName);
}

/**
 * 初始化渲染页面
 * @param {*} userName
 * @param {*} token 钉钉认证票据
 * ####注意### 按理应该只保留一个token的安全登录就行了。
 * 但是有如下特殊情况还是需要原登录接口：
 * 1. 钉钉生产环境给开发测试人员保留的登录入口 devUsers
 * 2. 开发调试模式下的移动端登录
 * 3. 第三方签名情况下的登录
 */
function initPage(userName, pwd, token) {
  if (isDD()) {
    deviceApi
      .device()
      .then((deviceInfo) => {
        !token ? realLoginUn(userName, pwd, deviceInfo.uuid, deviceInfo.platform) : realLoginTk(token);
      })
      .catch((err) => {
        deviceApi.alert && alert("获取钉钉设备信息失败:" + err);
      });
  } else {
    !token ? realLoginUn(userName, pwd, "1111", "H5") : realLoginTk(token);
  }
}

function initPageDing(userName, pwd, token) {
  deviceApi
    .device()
    .then((deviceInfo) => {
      !token ? realLoginUnDing(userName, pwd, deviceInfo.uuid, deviceInfo.platform) : realLoginTk(token);
    })
    .catch((err) => {
      deviceApi.alert("获取钉钉设备信息失败:" + err);
    });
}

// 钉钉登录 Mobile
function initPDingByMobile(mobile) {
  deviceApi
    .device()
    .then((deviceInfo) => {
      loginByMobile(mobile, deviceInfo.uuid);
    })
    .catch((err) => {
      deviceApi.alert("获取钉钉设备信息失败:" + err);
    });
}

/**
 * real 登录un
 */
function realLoginUn(userName, pwd, deviceId, platform) {
  // 登录
  loginService
    .loginDingTest(userName, pwd, deviceId)
    .then((dr) => {
      if (dr.success) {
        hideMcModal();
        hideLanuch();
        uni.setStorageSync("tk", dr.bean.tk);
        sessionStorage.setItem("tk", dr.bean.tk);
        store.state.userInfo = dr.bean;
        uni.setStorageSync("user", JSON.stringify(dr.bean));
        // 初始化字典数据
        app.$u.dic.dicDataInit();
        commonService.area();
        // 页面挂载
        app.$mount();
      } else {
        let errInfo = `【${userName}】登录失败,失败原因：${dr.msg}`;
        alert(errInfo);
      }
    })
    .catch((err) => {
      console.error("登录出错", err);
      alert("登录出错" + err);
    });
}

function realLoginUnDing(userName, pwd, deviceId, platform) {
  // 登录
  loginService
    .loginDingDing(userName, pwd, deviceId)
    .then((dr) => {
      if (dr.success) {
        hideMcModal();
        uni.setStorageSync("tk", dr.bean.tk);
        sessionStorage.setItem("tk", dr.bean.tk);
        store.state.userInfo = dr.bean;
        uni.setStorageSync("user", JSON.stringify(dr.bean));
        // 初始化字典数据
        app.$u.dic.dicDataInit();
        commonService.area();
        // 页面挂载
        app.$mount();
      } else {
        let errInfo = `【${userName}】登录失败,失败原因：${dr.msg}`;
        isDD() ? deviceApi.alert(errInfo) : alert(errInfo);
      }
    })
    .catch((err) => {
      console.error("登录出错", err);
      isDD() ? deviceApi.alert("登录出错" + err) : alert("登录出错" + err);
    });
}

function loginByMobile(mobile, deviceId) {
  // 登录
  loginService
    .loginMobile(mobile, deviceId)
    .then((dr) => {
      if (dr.success) {
        hideMcModal();
        uni.setStorageSync("tk", dr.bean.tk);
        sessionStorage.setItem("tk", dr.bean.tk);
        store.state.userInfo = dr.bean;
        uni.setStorageSync("user", JSON.stringify(dr.bean));
        // 初始化字典数据
        app.$u.dic.dicDataInit();
        commonService.area();
        // 页面挂载
        app.$mount();
      } else {
        let errInfo = `【${mobile}】登录失败,失败原因：${dr.msg}`;
        isDD() ? deviceApi.alert(errInfo) : alert(errInfo);
      }
    })
    .catch((err) => {
      console.error("登录出错", err);
      isDD() ? deviceApi.alert("登录出错" + err) : alert("登录出错" + err);
    });
}

/**
 * real 登录tk
 */
function realLoginTk(token) {
  // 登录
  loginService
    .loginByToken(token)
    .then((dr) => {
      if (dr.success) {
        hideMcModal();
        uni.setStorageSync("tk", dr.bean.tk);
        sessionStorage.setItem("tk", dr.bean.tk);
        store.state.userInfo = dr.bean;
        uni.setStorageSync("user", JSON.stringify(dr.bean));
        // 初始化字典数据
        app.$u.dic.dicDataInit();
        commonService.area();
        // 页面挂载
        app.$mount();
      } else {
        let errInfo = `【${userName}】登录失败,失败原因：${dr.msg}`;
        alert(errInfo);
      }
    })
    .catch((err) => {
      console.error("登录出错", err);
      alert("登录出错" + err);
    });
}

// 获取当前模块对应的agentId
function getAgentIdFromHref() {
  return process.uniEnv.AGENT_ID;
  // let modulePath = queryDdRouterPath();
  // return agentIdObj[modulePath];
}
// 从请求路径中获取模块路径path
function queryDdRouterPath() {
  let param = {};
  let search = window.location.search;
  if (search.indexOf("?") !== -1) {
    let queryString = search.substring(1);
    let qArr = queryString.split("&");
    qArr.forEach((r) => {
      let nv = r.split("=");
      param[nv[0]] = nv[1];
    });
  }
  return param["sys"];
}

function getUrlParam(pname) {
  let params = {};
  let queryStr = location.href.substring(location.href.indexOf("?") + 1);
  let queryArr = !!queryStr && queryStr.split("&");

  for (let i = 0; i < queryArr.length; i++) {
    let temp = queryArr[i].match("(.*?)=(.*)");
    let pkey = temp[1];
    let pval = decodeURI(decodeURI(temp[2]));
    if ("undefined" === typeof params[pkey]) {
      params[pkey] = pval;
    } else if ("string" === typeof params[pkey]) {
      params[pkey] = [params[pkey], pval];
    } else {
      params[pkey].push(pval);
    }
  }
  return pname ? params[pname] : params;
}

function showMcModal(un) {
  let mcModalDiv = document.getElementById("mcModal");
  let mcunInput = document.getElementById("mcun");
  mcunInput.value = un || "";
  let mcpwInput = document.getElementById("mcpw");
  let btn = document.getElementById("mcLogin");
  btn.onclick = function() {
    let mun = mcunInput.value || "";
    let mpw = mcpwInput.value || "";
    mpw = rsaUtil.encrypt(mpw);
    initPage(mun, mpw);
  };
  mcModalDiv.style.display = "flex";
}

function hideMcModal() {
  let mcModalDiv = document.getElementById("mcModal");
  if (mcModalDiv.style.display != "none") {
    mcModalDiv.style.display = "none";
  }
}

function hideLanuch() {
  let launchDiv = document.getElementById("launch");
  if (launchDiv.style.display != "none") {
    launchDiv.style.display = "none";
  }
}
